<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>酒店管理</span>
        <div class="search-container">
          <el-input v-model="searchName" placeholder="输入酒店名称搜索" clearable @clear="resetSearch" style="width: 250px;">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="searchHotel">搜索</el-button>
            </template>
          </el-input>
        </div>
        <el-button type="primary" @click="openCreateHotelDrawer">新增酒店</el-button>
      </div>
    </template>
    
    <div v-if="activeSearch" class="active-search">
      <el-tag closable @close="resetSearch">
        当前搜索: {{ activeSearch }}
      </el-tag>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="tableData.length === 0" class="empty-container">
      <el-empty description="暂无酒店数据" />
    </div>
    
    <el-table v-else :data="tableData" stripe style="width: 100%">
      <el-table-column prop="hotelName" label="酒店名称" sortable/>
      <el-table-column prop="country" label="国家" width="120"/>
      <el-table-column prop="city" label="城市" width="120"/>
      <el-table-column label="评分" width="180">
        <template #default="{ row }">
          <el-rate v-model="row.rating" disabled show-score text-color="#ff9900" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="480">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button type="primary" size="small" @click="viewHotelDetail(row)">查看详情</el-button>
            <el-button type="primary" size="small" @click="viewHotelRooms(row)">查看房间</el-button>
            <el-button type="info" size="small" @click="viewHotelReviews(row)">查看评价</el-button>
            <el-button type="warning" size="small" @click="openUpdateHotelDrawer(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.hotelName)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-box">
      <el-pagination background layout="total, sizes, prev, pager, next"
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[10, 20, 50, 100]"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :total="total"/>
    </div>
    
    <create-hotel ref="createHotelRef" @refresh="initData"/>
    <update-hotel ref="updateHotelRef" @refresh="initData"/>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getHotelList, deleteHotel, getHotelByName } from '@/api/hotel'
import { Edit, Delete, Location, Star, Search } from '@element-plus/icons-vue'
import CreateHotel from './components/CreateHotel.vue'
import UpdateHotel from './components/UpdateHotel.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserInfoStore } from '@/stores/userInfo'

const router = useRouter()
const route = useRoute()
const userInfoStore = useUserInfoStore()
const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(20) // 表格模式默认显示20条
const createHotelRef = ref()
const updateHotelRef = ref()
const loading = ref(true)
const searchName = ref('')
const activeSearch = ref('')

// 初始化数据，获取所有酒店列表
const fetchAllHotels = () => {
  console.log('开始请求所有酒店列表数据...');
  loading.value = true
  
  getHotelList({ pageIndex: pageIndex.value, pageSize: pageSize.value }).then(res => {
    processHotelResponse(res)
  }).catch(handleError);
}

// 按酒店名称搜索
const fetchHotelsByName = (name) => {
  if (!name) return
  
  console.log('开始按名称搜索酒店:', name);
  loading.value = true
  
  // 获取所有酒店，然后在前端筛选
  getHotelList({ pageIndex: 1, pageSize: 1000 }).then(res => {
    const result = res.data;
    
    if (result && result.code === 200) {
      // 前端进行模糊搜索（不区分大小写）
      const searchTerm = name.toLowerCase();
      const filteredData = Array.isArray(result.data) 
        ? result.data.filter(hotel => 
            hotel.hotelName.toLowerCase().includes(searchTerm) ||
            (hotel.city && hotel.city.toLowerCase().includes(searchTerm)) ||
            (hotel.country && hotel.country.toLowerCase().includes(searchTerm))
          )
        : [];
      
      tableData.value = filteredData;
      total.value = filteredData.length;
      
      if (filteredData.length === 0) {
        ElMessage.info('没有找到匹配的酒店');
      } else {
        console.log('按名称筛选后的酒店数据:', tableData.value);
      }
    } else {
      console.error('获取酒店列表失败:', result);
      ElMessage.error(result?.msg || '获取酒店列表失败');
    }
    
    loading.value = false;
  }).catch(handleError);
}

// 处理酒店响应数据
const processHotelResponse = (res) => {
  console.log('获取酒店列表响应:', res);
  
  const result = res.data;
  console.log('后端返回的原始数据结构:', result);
  
  if (result && result.code === 200) {
    tableData.value = Array.isArray(result.data) ? result.data : [];
    total.value = tableData.value.length;
    
    console.log('处理后的酒店数据:', tableData.value);
    
    if (tableData.value.length > 0) {
      console.log('第一条酒店数据的字段名:', Object.keys(tableData.value[0]));
    } else {
      console.log('酒店列表为空');
    }
  } else {
    console.error('获取酒店列表失败:', result);
    ElMessage.error(result?.msg || '获取酒店列表失败');
  }
  
  loading.value = false
}

// 处理错误
const handleError = (error) => {
  console.error('获取酒店列表错误:', error);
  ElMessage.error('网络错误，获取酒店列表失败');
  loading.value = false
}

// 初始化数据
const initData = () => {
  // 如果URL有搜索参数，优先处理
  if (route.query.searchName) {
    searchName.value = route.query.searchName as string
    activeSearch.value = searchName.value
    fetchHotelsByName(searchName.value)
  } else {
    fetchAllHotels()
  }
}

// 搜索酒店
const searchHotel = () => {
  if (!searchName.value) {
    resetSearch()
    return
  }
  
  activeSearch.value = searchName.value
  
  // 更新URL参数
  router.push({
    path: '/admin-hotel',
    query: { ...route.query, searchName: searchName.value }
  })
  
  fetchHotelsByName(searchName.value)
}

// 重置搜索
const resetSearch = () => {
  searchName.value = ''
  activeSearch.value = ''
  
  // 清除URL参数
  const query = { ...route.query }
  delete query.searchName
  router.push({ query })
  
  fetchAllHotels()
}

// 监听URL参数变化
watch(() => route.query.searchName, (newVal) => {
  if (newVal) {
    searchName.value = newVal as string
    activeSearch.value = newVal as string
    fetchHotelsByName(newVal as string)
  } else {
    // 如果URL参数被清除，恢复显示所有酒店
    if (activeSearch.value) {
      resetSearch()
    }
  }
}, { immediate: true })

const handleSizeChange = (size: number) => {
  pageSize.value = size
  initData()
}
const handleCurrentChange = (index: number) => {
  pageIndex.value = index
  initData()
}
const openCreateHotelDrawer = () => {
  createHotelRef.value.open()
}
const openUpdateHotelDrawer = (row: any) => {
  updateHotelRef.value.open(row)
}
const handleDelete = (hotelName: string) => {
  if (!hotelName) {
    ElMessage.error('酒店名称不能为空');
    return;
  }
  
  console.log('准备删除酒店:', hotelName);
  
  ElMessageBox.confirm('确定要删除该酒店吗？', '提示', { type: 'warning' }).then(() => {
    deleteHotel(hotelName).then(res => {
      console.log('删除酒店响应:', res);
      
      const result = res.data;
      if (result && result.code === 200) {
        ElMessage.success('删除成功')
        initData()
      } else {
        ElMessage.error(result?.msg || '删除失败')
      }
    }).catch(error => {
      console.error('删除酒店错误:', error);
      ElMessage.error('网络错误，删除酒店失败');
    });
  }).catch(() => {
    // 用户取消操作
    console.log('用户取消删除操作');
  });
}

// 查看酒店房间
const viewHotelRooms = (hotel: any) => {
  router.push({
    path: `/hotel/${encodeURIComponent(hotel.hotelName)}/rooms`
  });
}

// 查看酒店评价
const viewHotelReviews = (hotel: any) => {
  // 暂时跳转到评价列表页面，后续可以实现酒店评价详情页
  router.push({
    path: '/review',
    query: { hotelName: hotel.hotelName }
  });
}

// 查看酒店详情
const viewHotelDetail = (hotel: any) => {
  router.push({
    path: `/hotel/${encodeURIComponent(hotel.hotelName)}/detail`
  });
}

onMounted(() => {
  initData()
})
</script>
<style scoped>
.page-container {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-container {
  flex-grow: 1;
  margin: 0 20px;
  max-width: 400px;
}
.active-search {
  margin-bottom: 15px;
}
.loading-container, .empty-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.pagination-box {
  padding-top: 16px;
  display: flex;
  justify-content: right;
}
.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style> 